package com.cloud.observer;

import com.cloud.observer.handler.IExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.cloud.observer
 * @date:2021/1/19
 */
public class ScheduledExceptionHandler {

    @Autowired
    BaseScheduledObserver baseScheduledObserver;

    public void error(String key, Exception e) {
        ScheduledInfo info;
        String edition = UUID.randomUUID().toString().replaceAll("-", "");
        if (baseScheduledObserver.map.get(key) != null) {
            info = baseScheduledObserver.map.get(key);
            synchronized (info) {
                info.setEdition(edition);
                info.setException(e);
                info.setExceptionFlag(1);
                List<IExceptionHandler> errorHandlerList = info.getExceptionHandlerList();
                if (!errorHandlerList.isEmpty()) {
                    for (IExceptionHandler handler : errorHandlerList) {
                        handler.handle(e);
                        handler.send(e);
                    }
                }
                info.setExceptionFlag(0);
                info.getErrorSet().add(info.getEdition());
                baseScheduledObserver.map.put(key, info);
                return;
            }
        }
    }
}
